import React, { Component } from 'react'
import { Form, Row, Input, Col, Button, Table, Popconfirm, Icon, Modal, Checkbox } from 'antd';
import * as fetch from '../../utils/http'


class UserSetting extends Component {
    constructor(props) {
        super(props)
        this.state = {
            modalTitle: '新建用户',
            visibleUserModal: false,
            visibleRoleModal: false,
            userModel: {
                name: '',
                account: '',
                password: '',
                photo: '',
                phone: '',
                sex: 0,
                email: '',
                country: '',
                province: '',
                city: ''
            },
            currentUser: {

            },
            userList: [],
            userRoles: [],
            currentRoles: [],
            userId: '',
            saveUserRoles: []
        }
        this.getAllUser()
        this.getUserRoles()
    }

    getAllUser() {
        fetch.get('GasUser/GetUsers').then(res => {
            if (res.isSuccess) {
                this.setState({
                    userList: res.data
                })
            }
        })
    }

    getUserRoles() {
        fetch.get('GasRole/GetRoles').then(res => {
            if (res.isSuccess) {
                this.setState({
                    userRoles: res.data
                })
            }
        })
    }

    onDelUser(e) {
        const { id } = e
        if (id) {
            fetch.post('GasUser/Delete', { id }).then((res) => {
                if (res.isSuccess) {
                    this.getAllUser()
                }
            })
        }
    }

    showModal = () => {
        this.setState({
            visible: true,
        });
    }

    hideModal = () => {
        this.setState({
            visible: false,
        });
    }

    showNewModal(item) {
        this.setState({
            visibleUserModal: true,
            currentUser: item
        })
    }

    onMenuModalClose() {
        this.setState({
            visibleUserModal: false
        })
    }

    roleModalClose() {
        this.setState({ visibleRoleModal: false })
    }

    newUser = (visibleUserModal) => {
        const { currentUser } = this.state
        const ConfigForm = Form.create()(props => {
            const { form } = props
            const { getFieldDecorator } = form;

            const saveUser = () => {
                form.validateFields((err, values) => {
                    if (!err) {
                        console.log(values)
                        const params = Object.assign(this.state.userModel, values)
                        let url = values.id ? 'GasUser/Edit' : 'GasUser/Add'
                        fetch.post(url, params).then(res => {
                            if (res.isSuccess) {
                                this.getAllUser()
                                this.setState({
                                    visibleUserModal: false
                                })
                            }
                        })
                    }
                })
            }

            return (
                <Modal title={this.state.modalTitle}
                    cancelText='取消'
                    onCancel={this.onMenuModalClose.bind(this)}
                    onOk={saveUser}
                    okText='确定'
                    visible={visibleUserModal}
                >
                    <Form.Item label='id' className="hidden-input">
                        {getFieldDecorator('id', {
                            initialValue: currentUser.id
                        })(
                            <Input
                                readOnly={true}
                                className="h-40"
                                type="text"
                                placeholder="姓名"
                            />,
                        )
                        }
                    </Form.Item>
                    <Form className="login-form">
                        <Form.Item label="姓名" >
                            {getFieldDecorator('name', {
                                initialValue: currentUser.name,
                                rules: [{ required: true, message: '姓名必须输入' }]
                            })(
                                <Input
                                    className="h-40"
                                    type="text"
                                    placeholder="姓名"
                                />,
                            )}
                        </Form.Item>
                        <Form.Item label="账号" >
                            {getFieldDecorator('account', {
                                initialValue: currentUser.account,
                                rules: [{ required: true, message: '账号必须输入' }]
                            })(
                                <Input
                                    className="h-40"
                                    type="text"
                                    placeholder="账号"
                                />,
                            )}
                        </Form.Item>
                        {
                            currentUser.id ?
                                <div ></div> :
                                <Form.Item label="密码" >
                                    {getFieldDecorator('password', {
                                        initialValue: currentUser.password,
                                        rules: [{ required: true, message: '密码必须输入' }],
                                    })(
                                        <Input
                                            className="h-40"
                                            type="text"
                                            placeholder="密码"
                                        />,
                                    )}
                                </Form.Item>
                        }
                    </Form>
                </Modal>
            )
        })
        return <ConfigForm />
    }

    showUser(item) {
        const saveUserRolesId = item.userRoles.map(item => item.roleID)
        this.setState({
            userId: item.id,
            visibleRoleModal: true,
            saveUserRoles: saveUserRolesId || []
        })
    }

    onRoleChange(id) {
        const { saveUserRoles } = this.state
        if (saveUserRoles.includes(id)) {
            saveUserRoles.splice(saveUserRoles.indexOf(id), 1)
        } else {
            saveUserRoles.push(id)
        }
        this.setState({
            saveUserRoles
        })
    }

    addUserRole() {
        this.setState({
            visibleRoleModal: false
        })
        const { userId, saveUserRoles } = this.state
        fetch.post('GasUser/AddUserRole', {
            userID: userId,
            roleIDs: saveUserRoles
        }).then(res => {
            if (res.isSuccess) {
                this.getAllUser()
            }
        })
    }

    render() {
        const { visibleUserModal, userList } = this.state;
        const columns = [
            {
                title: '姓名',
                dataIndex: 'name',
                key: 'name'
            },
            {
                title: '用户名',
                dataIndex: 'account',
                key: 'account'
            },
            {
                title: '角色',
                render: item => (
                    <div style={{ fontSize: '14px', cursor: 'pointer' }} onClick={this.showUser.bind(this, item)} >
                        <Icon type="plus-square" style={{ marginRight: '5px' }}></Icon>
                        {
                            item.userRoles.length ?
                                item.userRoles.map((child, index) => {
                                    return (
                                        <span key={child.id}>{child.role.roleName}{index === (item.userRoles.length - 1) ? '' : '、'}</span>
                                    )
                                })
                                :
                                <span>暂无</span>
                        }
                    </div>
                )
            },
            {
                title: '操作',
                width: 80,
                render: item => (
                    <Row type="flex" justify="space-between">
                        <Col>
                            <Button type="primary" size="small" onClick={this.showNewModal.bind(this, item)} icon="form"></Button>
                        </Col>
                        <Col>
                            <Popconfirm
                                onConfirm={this.onDelUser.bind(this, item)}
                                title="确定删除吗？"
                                okText="删除"
                                cancelText="取消"
                                icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
                            >
                                <Button type="danger" size="small" icon="delete"></Button>
                            </Popconfirm>
                        </Col>
                    </Row>
                )
            }
        ];

        return (
            <div>
                <h3>用户设置</h3>
                <div className="d-flex ">
                    <Button className="m-r-10" onClick={this.showNewModal.bind(this)} type="primary" >新增</Button>
                </div>
                <div style={{ padding: '10px 0px' }}>
                    <Table bordered columns={columns} rowKey="id" dataSource={userList} size="middle" />
                </div>
                <Modal
                    cancelText='取消'
                    okText='确定'
                    title='用户角色'
                    onOk={this.addUserRole.bind(this)}
                    onCancel={this.roleModalClose.bind(this)}
                    visible={this.state.visibleRoleModal}>
                    <Checkbox.Group style={{ width: '100%' }} value={this.state.saveUserRoles} >
                        <Row>
                            {
                                this.state.userRoles.length > 0 &&
                                this.state.userRoles.map(item => {
                                    return (
                                        <Col key={item.id} span={8}>
                                            <Checkbox onClick={() => { this.onRoleChange(item.id) }} checked={this.state.saveUserRoles.includes(item.id)} value={item.id}>{item.roleName}</Checkbox>
                                        </Col>
                                    );
                                })
                            }
                        </Row>
                    </Checkbox.Group>
                </Modal>
                {
                    this.newUser(visibleUserModal)
                }
            </div>
        );
    }
}

export default UserSetting; 